package com.atung.parking.config.utils;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import org.springframework.stereotype.Component;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URL;
import java.net.URLConnection;
import java.nio.charset.StandardCharsets;
import java.time.DayOfWeek;
import java.time.LocalDate;
import java.util.*;

/**
 * @author Administrator
 */
@Component
public class QueryDataUtil {
    final static Map<Integer, Set<String>> holidays = new HashMap<>();

    static {
        LocalDate date = LocalDate.now();
        Integer year = date.getYear();
        Set<String> yearHoliday = getYearHoliday(year);
        holidays.put(year, yearHoliday);
    }

    public List<String> createWeekday() {
        List<String> data = new ArrayList<>();
        LocalDate today = LocalDate.now();
        LocalDate oneMonthLater = today.plusDays(30);
        for (LocalDate date = today; date.isBefore(oneMonthLater.plusDays(1)); date = date.plusDays(1)) {
            DayOfWeek dayOfWeek = date.getDayOfWeek();
            if (dayOfWeek != DayOfWeek.SATURDAY && dayOfWeek != DayOfWeek.SUNDAY) {
                data.add(date.toString());
            }
        }
        return data;
    }

    /**
     * 获取一个月后的节假日和周末（需要手动维护节假日列表）
     */
    public List<String> createHoliday() {
        List<String> data = new ArrayList<>();
        // 假设以下日期是节假日（需要根据实际情况维护）
        LocalDate today = LocalDate.now();
        int year = today.getYear();
        Set<String> holiday = holidays.get(year);
        LocalDate oneMonthLater = today.plusDays(30);
        for (LocalDate date = today; date.isBefore(oneMonthLater.plusDays(1)); date = date.plusDays(1)) {
            if (holiday.contains(date.toString())) {
                data.add(date.toString());
            }
        }
        return data;
    }

    /**
     * 获取一个月后的周末
      * @return
     */
    public List<String> createWeekend() {
        List<String> data = new ArrayList<>();
        LocalDate today = LocalDate.now();
        LocalDate oneMonthLater = today.plusDays(30);
        for (LocalDate date = today; date.isBefore(oneMonthLater.plusDays(1)); date = date.plusDays(1)) {
            DayOfWeek dayOfWeek = date.getDayOfWeek();
            if (dayOfWeek == DayOfWeek.SATURDAY || dayOfWeek == DayOfWeek.SUNDAY) {
                data.add(date.toString());
            }
        }
        return data;
    }

    public static Set<String> getYearHoliday(Integer currentYear) {
        // 节假日
        Set<String> hoSet = new TreeSet<>();
        // 获取免费API地址
        String httpUrl = "https://timor.tech/api/holiday/year/" + currentYear;
        BufferedReader reader = null;
        // 用于存储返回的年份节假日数据
        StringBuffer sbf = new StringBuffer();
        try {
            // 创建URL对象
            URL url = new URL(httpUrl);
            // 使用openConnection方法创建URLConnection对象
            URLConnection connection = url.openConnection();
            // 设置请求头
            connection.setRequestProperty("User-Agent", "Mozilla/4.76");
            connection.setRequestProperty("Accept-Language", "en-US,en;q=0.5");

            // 使用getInputStream方法获取输入流
            InputStream is = connection.getInputStream();
            // BufferedReader创建字节流对象，InputStreamReader将字节流转换为字符流，编码为utf8
            reader = new BufferedReader(new InputStreamReader(is, StandardCharsets.UTF_8));
            String strRead;
            while ((strRead = reader.readLine()) != null) {
                // 将每行内容追加到sbf字符串变量中
                sbf.append(strRead);
                sbf.append("\r\n");
            }
            reader.close();  // 关闭流
            // 字符串转json
            JSONObject json = JSON.parseObject(sbf.toString());
            // 根据holiday字段获取jsonObject内容
            JSONObject holiday = json.getJSONObject("holiday");
            if (holiday.size() == 0) {
                return hoSet;
            }
            // 记录哪些日期是调休上班的
            Set<String> workOnHoliday = new HashSet<>();
            // 添加从API获取的假期
            for (Map.Entry<String, Object> entry : holiday.entrySet()) {
                String value = entry.getValue().toString();
                JSONObject jsonObject = JSONObject.parseObject(value);
                String hoBool = jsonObject.getString("holiday");
                String date = jsonObject.getString("date");

                if ("true".equals(hoBool)) {
                    hoSet.add(date); // 添加节假日
                } else {
                    workOnHoliday.add(date); // 添加调休上班的日期
                }
            }

            // 获取当前年份的所有日期，判断哪些是周六和周日
            LocalDate startDate = LocalDate.of(currentYear, 1, 1);
            LocalDate endDate = LocalDate.of(currentYear, 12, 31);
            for (LocalDate date = startDate; !date.isAfter(endDate); date = date.plusDays(1)) {
                if ((date.getDayOfWeek() == DayOfWeek.SATURDAY || date.getDayOfWeek() == DayOfWeek.SUNDAY)
                        && !workOnHoliday.contains(date.toString())) {
                    hoSet.add(date.toString());  // 如果是周六或周日，且不是调休上班的日子，则添加到假期列表
                }
            }
        } catch (Exception e) {
            return hoSet;
        }

        // 返回Set集合，不需要排序，因为TreeSet会自动排序
        return (hoSet);
    }
}
